<template>
	<div class="home">
		<el-tabs v-model="activeName" @tab-click="handleClick">
			<el-tab-pane label="备份文件管理" name="first">
				<el-table :data="tableData" style="width: 100%">
					<el-table-column label="状态" width="180" align="center">
						<template slot-scope="scope">
							<i class="el-icon-s-order" v-if="scope.row.status==1"
								style="color: green;font-size: 30px;"></i>
							<i class="el-icon-s-order" v-else style="color: red;font-size: 30px"></i>
						</template>
					</el-table-column>
					<el-table-column prop="time" label="备份时间" width="180"></el-table-column>
					<el-table-column prop="fileName" label="文件名"></el-table-column>
					<el-table-column prop="fileSize" label="大小"></el-table-column>
					<el-table-column label="操作" width="120">
						<template slot-scope="scope">
							<i class="el-icon-close" style="color: red;font-size: 30px"
								@click="deleteRow(scope.$index, scope.row)"></i>
						</template>
					</el-table-column>
				</el-table>
			</el-tab-pane>
			<el-tab-pane label="系统设置" name="second">
				<el-form ref="systemForm" :model="form" label-width="180px" :rules="rules">
					<h6>自动备份设置：</h6>
					<el-form-item label="按月自动备份，每月" prop="month">
						<el-col :span="20">
							<el-input v-model="form.month"></el-input>
							<span>说明：可输入多项以,分割</span>
						</el-col>
						<el-col :span="4">&nbsp;号自动备份</el-col>
					</el-form-item>
					<el-form-item label="按周自动备份，每周周" prop="week">
						<el-col :span="20">
							<el-input v-model="form.week"></el-input>
							<span>说明：可输入多项以,分割</span>
						</el-col>
						<el-col :span="4">&nbsp;自动备份</el-col>
					</el-form-item>
					<el-form-item label="备份时刻" prop="time">
						<el-col :span="6">
							<el-time-picker style="width: 100%" :editable="false" v-model="form.time"
								placeholder="任意时间点" format="HH:mm" value-format="HH:mm">
							</el-time-picker>
						</el-col>
					</el-form-item>
					<el-form-item label="备份数据库设置" prop="dbs">
						<el-checkbox-group v-model="form.dbs" style="width: 100%">
							<el-checkbox label="A库" name="type"></el-checkbox>
							<el-checkbox label="B库" name="type"></el-checkbox>
						</el-checkbox-group>
					</el-form-item>
					<el-form-item label="自动清除设置" prop="purge">
						<el-switch v-model="form.purge"></el-switch>
					</el-form-item>
					<el-form-item label="备份文件保留数量" prop="reserved">
						<el-col :span="8">
							<el-input v-model="form.reserved"></el-input>
						</el-col>
					</el-form-item>
					<el-form-item label="备份路径" prop="location">
						<el-input v-model="form.location"></el-input>
					</el-form-item>
					<el-form-item>
						<el-button type="primary" @click="onSubmit">保存</el-button>
						<el-button @click="backDefault">取消</el-button>
					</el-form-item>
				</el-form>
			</el-tab-pane>
			<el-tab-pane label="立即备份" name="third">
				<el-form ref="backForm" :model="backForm" label-width="180px" :rules="backRules">
					<el-form-item label="选择备份的数据库"  prop="dbs">
						<el-checkbox-group v-model="backForm.dbs" style="width: 100%">
							<el-checkbox label="A库" name="type"></el-checkbox>
							<el-checkbox label="B库" name="type"></el-checkbox>
						</el-checkbox-group>
					</el-form-item>
					<el-form-item>
						<el-button type="primary" @click="zhixing">执行备份</el-button>
					</el-form-item>
				</el-form>
				<el-progress :text-inside="true" :stroke-width="26" :percentage="percentage"></el-progress>
			</el-tab-pane>
		</el-tabs>
	</div>
</template>

<script>
	import VueWS from "vue-websocket";
	export default {
		mixins: [VueWS],
		data() {
			//校验是否只有数字和，
			let checkPriceSell = (rule, value, callback) => {
				if (value) {
					if (!/^([0-9]*[1-9][0-9]*)(,([0-9]*[1-9][0-9]*))*?$/.test(value)) {
						callback("请输入数字，多项以,隔开")
					} else {
						callback();
					}
				} else {
					callback();
				}
			}
			let checkNumSell = (rule, value, callback) => {
				if (value) {

					if (!/^[0-9]*?$/.test(value)) {
						callback("请输入数字")
					} else {
						callback();
					}
				} else if (!value) {
					callback();
				} else {
					callback();
				}
			}
			return {
				activeName: "first",
				tableData: [],
				form: {
					month: "",
					week: "",
					time: "",
					dbs: [],
					purge: false,
					reserved: "",
					location: "",
				},
				rules: {
					month: [{
						required: false,
						trigger: ['blur', 'change'],
						message: '只能输入数字并以,隔开',
						validator: checkPriceSell
					}],
					week: [{
						required: false,
						trigger: ['blur', 'change'],
						message: '只能输入数字并以,隔开',
						validator: checkPriceSell
					}],
					time: [{
						required: true,
						message: '请选择备份时刻',
						trigger: 'change'
					}],
					dbs: [{
						type: 'array',
						required: true,
						message: '请至少选择一个数据库',
						trigger: 'change'
					}],
					reserved: [{
						required: true,
						message: '请输入备份文件保留数量',
						trigger: 'blur',
					}, {
						message: '只能输入数字',
						type: 'number',
						validator: checkNumSell
					}]

				},
				backForm: {
					dbs: []
				},
				backRules:{
					dbs: [{
						type: 'array',
						required: true,
						message: '请至少选择一个数据库',
						trigger: 'change'
					}]
				},
				scoket: '',
				percentage: 0,//进度值
				count: 0,
			};
		},
		created() {
			this.getTableList();
			//连接webSocket
			this.connect("ws://localhost:8999/api/websocket/1");
		},
		methods: {
			//获取表格数据
			getTableList() {
				//获取备份文件列表
				this.$http.get(`file/page`).then(res => {
					console.log(res)
					const {
						code,
						data
					} = res.data
					if (code == 200) {
						this.tableData = data
					}
				})
			},
			//点击标签页事件
			handleClick(tab, event) {
				// console.log(tab, event);
				if (tab.index == 0) { //备份文件列表
					this.$http.get(`file/page`).then(res => {
						const {
							code,
							data
						} = res.data
						if (code == 200) {
							this.tableData = data.records
							this.tableTotal = data.total
						}
					})
				} else if (tab.index == 1) { //系统设置
					this.$refs.systemForm.resetFields()
				} else if(tab.index == 2) { //立即备份
					this.$refs.backForm.resetFields();
					
					//进度条置为0
					if(this.percentage >= 100){
						this.percentage = 0
					}
				}
			},
			//删除文件事件
			deleteRow(index, row) {
				console.log(row)
				//删除文件方法
				this.$http.delete(`file/deleteFile/${row.id}`).then(res => {
					const {
						success
					} = res.data
					if (success) {
						this.$message.success('删除文件成功！');
						this.getTableList();
					} else {
						this.$message.error('删除文件失败！');
					}
				})
			},
			//提交保存设置信息
			onSubmit() {
				this.$refs["systemForm"].validate((valid) => {
					if (valid) {
						this.$http.post(`taskConfig/update`, this.form).then(res => {
							const {
								code
							} = res.data
							if (code == 200) {
								this.$message.success('更新设置成功！');
								this.$refs.systemForm.resetFields()
							} else {
								this.$message.error('更新设置失败');
							}
						})
					} else {
						return false;
					}
				})
			},
			//系统设置取消
			backDefault() {
				this.$refs.systemForm.resetFields()
			},
			//立即执行事件
			zhixing() {
				this.$refs["backForm"].validate((valid) => {
					//db: 
					if (valid) {
						let db = this.backForm.dbs.toString(",")
						this.$http.get(`file/db?db=${db}`).then(res => {
							console.log(res)
						})
					} else {
						return false;
					}
				})
			},
			//连接websocket
			connect(url) {
				// 实例化socket
				this.socket = new WebSocket(url)
				// 监听socket连接
				this.socket.onopen = this.open
				// 监听socket错误信息
				this.socket.onerror = this.error
				// 监听socket消息
				this.socket.onmessage = this.getMessage
			},
			//socket连接
			open() {
				console.log("socket连接成功")
			},
			//socket错误信息
			error() {
				console.log("连接错误")
			},
			//接收发送的数据
			getMessage(data) {				
				let fileInfo = JSON.parse(data.data);
				//判断是文件信息数据还是进度数据
				if(fileInfo.id){
					//判断表格数据是否存在推送的数据
					// this.tableData.forEach((item,index) =>{
					// 	if(item[0].id == fileInfo.id){
					// 		this.tableData[0]=fileInfo
					// 	}else {
					// 		this.tableData.unshift(fileInfo)
					// 	}
					// })
				}else{
					this.percentage = data.data
				}
				

			},
		},
	};
</script>

<style scoped>
	.home {
		width: calc(50% - 20px);
		height: calc(50% - 20px);
		padding: 10px;
		margin: 0 auto;
	}
</style>